# coding:utf8
from django.views import View
from django.http import JsonResponse
import json

# 为了专注于演示接口的开发，这里没有使用数据库，只是用了一个list作为存储容器
tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'done': False
    }
]


class TodoList(View):

    def get(self, request):
        """获取所有task"""
        return JsonResponse(tasks, safe=False)

    def post(self, request):
        """添加一个task"""
        data = json.loads(request.body)
        try:
            task = {
                "id": tasks[-1]['id'] + 1,
                'title': data['title'],
                'done': False
            }
            tasks.append(task)
        except Exception as err:
            return JsonResponse({{"errcode": 4001, "errmsg": "任务添加失败"}})
        else:
            return JsonResponse(task, safe=False)


class Todo(View):
    def get(self, request, task_id):
        """获得某个task"""
        task_id = int(task_id)
        task = list(filter(lambda t: t['id'] == task_id, tasks))
        if not task:
            return JsonResponse({"code": 400})
        return JsonResponse({'task': task[0]})

    def delete(self, request, task_id):
        """删除某个task"""
        task_id = int(task_id)
        task = list(filter(lambda t: t['id'] == task_id, tasks))
        if task:
            tasks.remove(task)
        return JsonResponse({'result': True})

    def put(self, request, task_id):
        """修改某个task"""
        task_id = int(task_id)
        data = json.loads(request.body)
        task = list(filter(lambda t: t['id'] == task_id, tasks))
        if len(task) == 0:
            return JsonResponse({"code": 400})
        if not data:
            return JsonResponse({"code": 400})
        if data.get('title') is None:
            return JsonResponse({"code": 400})
        if data.get('done') and type(data['done']) is not bool:
            return JsonResponse({"code": 400})
        task[0]['title'] = data.get('title', task[0]['title'])
        task[0]['done'] = data.get('done', task[0]['done'])
        return JsonResponse({'task': task[0]})
